<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="utf-8">
    <title></title>
    {% load staticfiles %}
    <link rel="stylesheet" href="{% static "css/css.css" %}">
    <link rel="stylesheet" href="{% static "css/cropper.min.css" %}">
    <link rel="stylesheet" href="{% static "css/webuploader.css" %}">
</head>
<script type="text/javascript">
$(function(){
         $("#btnSubmit").click(function(){
            var val=$('input:radio[name="is_publish_clock"]:checked').val();
            if(val==1){
                $(".set-timing").show()
            }
         });
     });
</script>
<body>
<form action="{% url 'chapter_publish' %}" method="post">
    <div class="content">
        <div class="form-box upload-box">
            <div class="line-box">
                <label>发布平台</label>
                <input type="checkbox" name="platform" value="qq">腾讯动漫
                <input type="checkbox" name="platform" value="netEase">网易动漫
                <input type="checkbox" name="platform" value="qingdian">轻点动漫
                <input type="checkbox" name="platform" value="maimeng">麦萌动漫

            </div>
            <div class="line-box">
                <label>作品名称：</label>
                <input type="text" name="works_name" value="" class="fb-input">
            </div>
            <div class="line-box">
                <label>作品ID(腾讯必填,其他不填)：</label>
                <input type="text" name="works_id" value="" class="fb-input">
            </div>
            <div class="line-box">
                <label>章节名称：</label>
                <input type="text" name="chapter_name" value="" class="fb-input">
            </div>

            <div class="line-box clearfix">
                <label>轻点封面：</label>
                <div class="cover-box clearfix" id="qingdian-cover" company="qingdian">
                    <div class="show-image">

                    </div>
                    <input name="qingdian_cover_image" type="hidden" value="">
                    <a href="javascript:void(0)" class="upload-btn">上传封面</a>
                </div>
            </div>
            <div class="line-box clearfix">
                <label>腾讯封面：</label>
                <div class="cover-box clearfix" id="tencent-cover" company="tencent">
                    <div class="show-image">

                    </div>
                    <input name="qq_cover_image" type="hidden" value="">
                    <a href="javascript:void(0)" class="upload-btn">上传封面</a>
                </div>
            </div>
            <div class="line-box clearfix">
                <label>章节图片：</label>
                <div class="right-box clearfix">
                    <div class="upload-item add-img" id="add-btn">上传<br>章节</div>
                </div>
            </div>
            <div class="line-box" >
                <label for="timing">是否定时：</label><input type="radio" name="is_publish_clock" value="0" checked='checked'/>否
                <input type="radio" id="timing" name="is_publish_clock" value="1">是
            </div>
            <div class="line-box set-timing">
                <label>腾讯</label><input type="text" name="qq_publish_clock_time" value="" class="fb-input">
                <Br><Br>
                <label>网易</label><input type="text" name="netEase_publish_clock_time" value="" class="fb-input">
                <br><br>
                <label>麦萌</label><input type="text" name="maimeng_publish_clock_time" value="" class="fb-input">

            </div>
            <div class="line-box clearfix">
                <button type="submit">提交</button>
            </div>
        </div>
    </div>

    <!-- 封面裁剪弹出 -->
    <div class="dialog-content cover-cut-dialog" id="qingdian-dialog">
        <div class="dialog-box cover-cut-box">
            <div class="select-img">
                选择本地图片
                <input type="file" name="article_artwork" id="inputImage">
            </div>
            <!-- 显示剪裁 -->
            <div class="cropper-wrap-content">
                <img src="" alt="" id="image">

                <!-- <div class="cwc-tips">
                    仅支持jpg png图片格式，且文件小于1.5M，<br>
                    图片尺寸需大于600x600
                </div> -->
            </div>
            <!-- 显示剪裁 end -->

            <!-- 操作剪裁 -->
            <div class="cropper-ctrl-content clearfix">
                <div class="cc-item cc-scale-box">
                    <span class="cc-scale-btn cc-scale-minify"></span>
                    <!-- <div class="cc-scale-rule">
                        <span class="cc-scale"></span>
                    </div> -->
                    <span class="cc-scale-btn cc-scale-magnify"></span>
                </div>
                <div class="cc-item cc-rotate"></div>
            </div>
            <!-- 操作剪裁 end -->
            <!-- 保存 取消 -->
            <div class="cropper-btn-box">
                <span class="cbb-btn cbb-save-btn">保存</span>
                <span class="cbb-btn cbb-cancel-btn">取消</span>
            </div>
            <!-- 保存 取消 end -->
            <!--关闭剪裁窗口-->
            <span class="cropper-close"></span>
            <!--关闭剪裁窗口 end -->
        </div>
    </div>
</form>
<!-- 封面裁剪弹出 end -->


<script src="{% static "js/jquery-3.2.1.min.js" %}" charset="utf-8"></script>
<script src="{% static "js/cropper.min.js" %}" charset="utf-8"></script>
<script src="{% static "js/webuploader.js" %}"></script>
<script type="text/javascript">
     //作品名 章节名 ID  封面  是否定时上传   定时上传时间
    $(".upload-btn").click(function () {
        company = $(this).parents(".cover-box").attr("company");
        $(".cover-cut-dialog").show();
    })


    //标记当前上传的是哪个站的封面
    var company = "";
    //存贮图片信息
    var imageSource = {}

    // 裁剪图片上传
    var isReady;
    var URL = window.URL || window.webkitURL;

    var $image = $("#image");
    var maxSize = 2 * 1024 * 1024;
    var cropperOptions = {
        //裁剪比例
        aspectRatio: 1.875,
        dragMode: "move",
        //viewMode3:the container should be within the canvas
        viewMode: 1,
        cropBoxResizable: false,
        //剪裁区域占比
        autoCropArea: 0.81,
        // cropBoxMovable:false
    }


    var $inputImage = $("#inputImage");
    var blobURL;
    var type;
    if (URL) {
        $inputImage.on('change', function (event) {
            var files = this.files;
            console.log(event)
            var file;
            isReady = false;
            file = files[0];
            var size = file.size;
            console.log(files);
            blobURL = URL.createObjectURL(file);
            //满足大小
            var isMeetsSize = true;
            //是否满足格式
            var isMeetsType = true;

            if (size > maxSize) {

                isMeetsSize = false;
            }

            if (!/.(jpg|jpeg|png|GIF|JPG|png)$/.test(file.type)) {
                isMeetsType = false;
            } else {
                type = file.type;
            }

            var img = new Image();
            img.src = blobURL;
            img.onload = function () {
                if (this.naturalWidth < 600 || this.naturalHeight < 600) {
                    alert("图片尺寸不应小于600*600")
                    $image.cropper("destroy");
                } else {
                    if (isMeetsType) {

                        if (isMeetsSize) {
                            $image.cropper(cropperOptions);
                            setTimeout(function () {
                                $image.cropper('replace', blobURL);
                            }, 1);
                        } else {
                            alert("图片大小不能超过1.5MB")
                        }
                    } else {
                        alert("图片只支持JPG,PNG")
                    }
                }
            }


        })
    }

    $image.on("ready", function () {
        isReady = true;
    })

    //旋转,每次+90
    $(".cc-rotate").click(function (event) {
        if (isReady) {
            $image.cropper("rotate", 90);
        }
    });
    //点击缩放：缩小
    $(".cc-scale-minify").click(function (event) {
        if (isReady) {
            $image.cropper("zoom", -0.1);
        }
    });

    //点击缩放：放大
    $(".cc-scale-magnify").click(function (event) {
        if (isReady) {
            $image.cropper("zoom", 0.1);
        }
    });

    //保存
    $(".cbb-save-btn").click(function (event) {
        if (isReady) {
            var data = $image.cropper('getCroppedCanvas', {
                width: 1125,
                height:600
            });
            $("#croppedImg").html('<img src="' + data.toDataURL() + '">');
            var base64 = data.toDataURL();

            // $("#base64").val(base64.split(",")[1]);
            $("#" + company + "-cover .show-image").html()
            $(".cover-cut-dialog").hide();
            imageSource[company] = base64.split(",")[1];
            $.post("{% url 'chapter_image_save' %}", {'image_str': imageSource[company]}, function (data) {
                $("#" + company + "-cover .show-image").html("<img src=" + base64 + ">");

                $("#" + company + "-cover   input").val(data.image_name);
            })


            // var str=base64.substring(22);
            // var strLength = base64.length;
            //
            // var equalIndex= str.indexOf("=");
            // if(str.indexOf("=")>0)
            // {
            //     str=str.substring(0, equalIndex);
            //
            // }
            // var strLength=str.length;
            // var fileLength=parseInt(strLength-(strLength/8)*2);
            // console.log(fileLength)

        } else {
            alert("您还没有上传封面图片")
        }
    });


    $(".cropper-close").click(function () {
        $(".cover-cut-dialog").hide();
    })


    //定时
    $("#timing").on("change", function () {
        var checked = $(this)[0].checked;
        if (checked) {
            $(".set-timing").show()
        } else {
            $(".set-timing").hide()
        }
    })


    //上传
    //上传图片按钮
    var $addBtn = $(".add-img");
    var article_id = 10000;
    //创建文件上传
    var uploader = WebUploader.create({
        auto: true,
        // swf文件路径
        swf: '/js/Uploader.swf',

        // 文件接收服务端。
        server: '{% url 'upload_file' %}',

        //文件类型
        accept: {
            extensions: "png,jpg,jpeg",
            mimeTypes: "image/jpg,image/jpeg,image/png"
        },
        formData: {
            article_id: article_id,
            articleType: "article_ext"
        },
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: '#add-btn',

        // 图片在上传前不进行压缩
        compress: false,
        //并发数
        threads: 1,
        //验证单个文件大小是否超出限制, 超出则不允许加入队列
        fileSingleSizeLimit: 2 * 1024 * 1024,
        //文件个数
        fileNumLimit: 99
    });

    //上传结束监听
    uploader.on('uploadComplete', function (file) {


    });

    //选择路径监听
    uploader.on('fileQueued', function (file) {

        var html = getViewTemplate(file.id);
        var $item = $(html);
        var $img = $item.find("img");
        $addBtn.before($item);
        var $li = $('#' + file.id);
        //获取文件大小
        var size = file.size;
        //判断文件大小
        if (size < 2 * 1024 * 1024) {
            uploader.makeThumb(file, function (err, src) {
                $img[0].setAttribute("src", src);

                //添加删除按钮事件

                $li.find(".close-btn").click(function (event) {
                    uploader.cancelFile(file);
                    $(this).parents(".upload-item").remove();
                });
            })
        } else {

            alert("超过2MB")
            uploader.cancelFile(file);
            $li.find(".status-uploading").hide();
            $li.find(".status-fail").show();
        }


    });
    //错误
    uploader.on("error", function (type) {
        if (type == "Q_TYPE_DENIED" || type == "F_EXCEED_SIZE") {
            alert("只支持PNG,JPG格式,大小2M以内")
        }


    })

    //上传进度
    uploader.on('uploadProgress', function (file, percentage) {
        var $li = $('#' + file.id),
            $percent = $li.find('.status-uploading span');
        $percent.text(parseInt(percentage * 100) + "%");
    });

    //上传失败
    uploader.on('uploadError', function (file) {
        var $fildEle = $('#' + file.id);
        $fildEle.find(".status-fail").show();
        $fildEle.find(".status-uploading").hide();
        $fildEle.find("img").remove();
        $fildEle.find(".close-btn").show();

    });

    //上传成功
    uploader.on('uploadSuccess', function (file, response) {
        var $fildEle = $('#' + file.id);

        var imgId = response.data.articleExtId;
        $fildEle.attr("imgId", imgId);
        var imgUrl = response.data.url;
        $fildEle[0].imgUrl = imgUrl;
        html_str = $fildEle.html();
        $fildEle.html(html_str + '<input type="hidden"  name="chapter_imgs" value="' + response.data + '">')
        //为子项添加图片id,并且增加上传成功的标识
        //$( '#'+file.id ).attr("imgId",responese.imgId).addClass('uploaded');
        $fildEle.addClass("uploaded").find(".status-uploading").hide();
        $fildEle.addClass("uploaded").find(".status-fail").hide();

    });

    function getViewTemplate(id) {
        var html = "";
        html += "<div class='upload-item' id='" + id + "''>";
        html += "<div class='ui-box'>";
        html += "<div class='view-box'>";
        html += "<img>";
        html += "</div>";
        html += "<div class='status-uploading'>";
        html += "正在上传<span>0%</span>";
        html += "</div>";
        html += "<div class='status-fail'><span>上传失败</span>重新上传</div>";
        html += "<span class='close-btn'></span>";
        html += "</div>";
        html += "</div>";
        return html;
    }
</script>
</body>
</html>
